<?php

namespace common\helpers;

use Yii;

/**
 * Class LogHelper
 * @package common\helpers
 *
 */
class LogHelper
{
    const LOG_LEVEL_DEBUG = 0;
    const LOG_LEVEL_INFO = 1;
    const LOG_LEVEL_NOTICE = 2;
    const LOG_LEVEL_WARNING = 3;
    const LOG_LEVEL_ERROR = 4;

    private $logDir;

    function __construct(string $logDir = null)
    {
        if (empty($logDir)) {
            $logDir = Yii::getAlias('@log');
//            $targetDir = $path . '/tmp/video_first_img/';
//            !is_dir($targetDir) && mkdir($targetDir, 0777, true);
        }
        $this->logDir = $logDir;
    }

    /**
     * 写入日志
     * @param string $msg
     * @param int $logLevel
     * @return string
     */
    public static function log(string $msg, int $logLevel = self::LOG_LEVEL_INFO): string
    {
        $time = time();
        $date = date('Y-m-d H:i:s', $time);
        $day = date('Ymd', $time);

        $self = new static();
        $levelStr = $self->levelMap($logLevel);
        $targetDir =  $self->logDir . "/{$levelStr}/";
        !is_dir($targetDir) && mkdir($targetDir, 0777, true);
        $filePath = $targetDir . "/{$day}.log";
        $str = "[{$date}] : [{$msg}]\n";
        file_put_contents($filePath, "{$str}", FILE_APPEND | LOCK_EX);
        return $str;
    }

    function console(?string $msg, int $logLevel = self::LOG_LEVEL_INFO)
    {
        $date = date('Y-m-d H:i:s');
        $levelStr = $this->levelMap($logLevel);
        $temp = "[{$date}][{$levelStr}]:[{$msg}]\n";
        fwrite(STDOUT, $temp);
    }

    private function levelMap(int $level)
    {
        switch ($level) {
            case self::LOG_LEVEL_DEBUG:
                return 'debug';
            case self::LOG_LEVEL_INFO:
                return 'info';
            case self::LOG_LEVEL_NOTICE:
                return 'notice';
            case self::LOG_LEVEL_WARNING:
                return 'warning';
            case self::LOG_LEVEL_ERROR:
                return 'error';
            default:
                return 'unknown';
        }
    }
}
